﻿/*
 * PsTFS is a set of PowerShell commands to manage and use Team Foundation Server. PowerShell 
 * effectiveness is combined with the power of TFS API to maximizes TFS capabilities.
 * 
 * Creator : Choulant Noham
 * Mail : choulant@gmail.com
 * Blog : http://choulant.blogspot.com
 * 
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using PsTFS.Provider;
using PsTFS.Objects;
using PsTFS.Objects.Methodes;

namespace PsTFS.Commandes.Get
{
    /// <summary>
    /// Récupération des changesets
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "Changeset")]
    public class Get_Changeset : PsCmdlet
    {
        /// <summary>
        /// Lancement du processus de récupération de changeset
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                // Get a reference to the version control service
                VersionControlServer versionControl = Methode_Service.VCS();

                if (this.Path == null)
                {
                    this.Path = string.Empty;
                }

                if (this.Path.Contains('$'))
                {
                    this.Path = this.Path;
                }
                else
                {
                    this.Path = "$/" + this.Path;
                }

                IEnumerable cs = versionControl.QueryHistory(this.Path, VersionSpec.Latest, 0, RecursionType.Full, null /* ou alors, le nom d'un utilisateur */, null, null, Int32.MaxValue, true, true);
                
                var ls = cs.Cast<Changeset>().Where(c => c.Changes.Length > 0).ToList();
                
                //Retourne un objet
                WriteObject(ls);
            }
            catch (Exception ex)
            {
                ErrorRecord err = new ErrorRecord(ex,Error.GetInstance().GetError(this), ErrorCategory.WriteError, null);
                WriteError(err);
                Log.AddLog(ex.StackTrace);
            }
        }


        /// <summary>
        /// Permet d'informer la fin de la commande
        /// </summary>
        protected override void EndProcessing()
        {
            Log.AddLog(null, "Get-Changeset is end");
            base.EndProcessing();
        }

        /// <summary>
        /// Object contenant Team Foundation Server
        /// </summary>
        [Parameter(Position = 0)]
        public TeamFoundationServer TFS
        {
            set { Context.GetContext().Tfs = value; }
        }
        /// <summary>
        /// Emplacement depuis le quel récupérer les changesets
        /// </summary>
        [Parameter(Position = 1)]
        public String Path{ get;set;}
    }
}